import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Card, Drawer, Icon, message, Popconfirm, Table } from 'antd';

import TreeMultiSelect from '@/components/TreeMultiSelect';
import AlarmDetail from '@/components/AlarmDetail';


class AlarmCard extends Component {

  constructor(props) {
    super(props);
    this.state = {
      searchParams: [],
      treeSelectValue: [],
      drawerVisible : false,
      alarm: {}
    };
    this.extra = (
      <Button type='primary' onClick={() => this.searchData()}>
        <Icon type='search'/>Search
      </Button>
    );
    this.columns = [{
    //   title: 'Ord',
    //   dataIndex: 'ord',
    //   key: 'ord',
    //   width: '16%',
    // }, {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: '11%',
    }, {
      title: '告警源',
      dataIndex: 'source',
      key: 'source',
      width: '11%',
    }, {
      title: '告警信息',
      dataIndex: 'msgText',
      key: 'msgText',
      width: '17%',
    }, {
      title: '告警源状态',
      dataIndex: 'sourceState',
      key: 'sourceState',
      width: '11%',
    }, {
      title: '告警分类',
      dataIndex: 'alarmClass',
      key: 'alarmClass',
      width: '11%',
    }, {
      title: '响应时间',
      dataIndex: 'ackTime',
      key: 'ackTime',
      width: '11%',
    }, {
      title: '详情',
      render: (record) => {
        return (
          <span>
              <a onClick={()=>this.showDrawer(record)}>{record.count}</a>
          </span>
        )
      },
      width: '17%',
    }, {
      title: '操作',
      render: (record) => {
        return (
          <span>
            <Popconfirm title='Confirm this alarm?' onConfirm={() => this.ackAllAlarm(record.ord)}>
              <a>确认</a>
            </Popconfirm>
          </span>
        )
      },
      width: '11%',
    }];
  }

  searchData = () => {
    const { treeSelectValue } = this.state;
    if(!treeSelectValue || treeSelectValue.length===0) {
      message.error('请选择告警查询参数');
    } else {
      const h = (typeof treeSelectValue)==='string'?treeSelectValue:treeSelectValue.join('|||');
      const payload = {h, pageNo:1};
      this.props.dispatch({type: 'alarmData/fetch', payload});
    }
  }

  handlePageChange = (changePageNo) => {
    const { pageNo, dispatch } = this.props;
    if (changePageNo !== pageNo) {
      dispatch({ type: 'alarmData/fetch', payload: { pageNo: changePageNo } });
    }
  };

  initSearchParams = (searchParams) => (searchParams.map((searchParam)=> {
    if(searchParam.children) {
      searchParam.selectable = false;
      searchParam.children = searchParam.children.map((item)=>({
        title: item.title,
        value: item.title+'||'+item.alarmClassOrd,
        key: item.key
      }));
      return searchParam;
    } else {
      return {
        title: searchParam.title,
        value: searchParam.title+'||'+searchParam.alarmClassOrd,
        key: searchParam.key
      }
    }
  }));

  ackAllAlarm = (ord)=>{
    this.props.dispatch({
      type: 'alarmData/ackAllAlarm',
      payload: ord,
    }).then(response => {
      if (response && typeof response.state !== undefined && response.state === 0) {
        message.success(response.message || '确认成功');
        this.reload();
      } else {
        message.error('确认失败');
      }
    });
  }

  reload = ()=> {
    this.searchData();
  }

  showDrawer = (record) => {
    this.setState({
      drawerVisible: true,
      alarm: record
    });
  };

  onClose = () => {
    this.setState({
      drawerVisible: false,
    });
  };

  componentDidMount() {
    this.setState({
      searchParams: this.initSearchParams(this.props.searchParams),
      treeSelectValue: [],
      drawerVisible : false,
      alarm: {}
    })
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.searchParams !== this.props.searchParams) {
      this.props.searchParams = nextProps.searchParams;
      this.setState({
        searchParams: this.initSearchParams(this.props.searchParams),
        treeSelectValue: [],
        drawerVisible : false,
        alarm: {}
      });
    }
  }

  render() {
    const { list, total, pageNo, pageSize, loading } = this.props;
    const { searchParams, treeSelectValue, drawerVisible, alarm } = this.state;
    const title = (
      <span>
        <TreeMultiSelect
          style={{margin: '0 10px', width: 300}}
          value={treeSelectValue}
          treeData={searchParams}
          onChange={treeSelectValue=>this.setState({treeSelectValue})}
          placeholder='选择查询参数'
          // multiple={showType==='line'}
          // treeCheckable={showType==='line'}
        />
      </span>
    );
    return (
      <Card title={title} extra={this.extra} style={{overflowX: 'hidden', height: '100%'}}>
        <Table
          className={'table-wrapper'}
          columns={this.columns}
          dataSource={list}
          rowKey='_id'
          loading={loading}
          pagination={{
            total: total,
            pageSize: pageSize,
            current: pageNo,
            onChange: this.handlePageChange,
          }}
        />
        <Drawer
          title={'告警详情 - '+alarm.source+':'}
          placement='right'
          closable={false}
          onClose={this.onClose}
          visible={drawerVisible}
          getContainer={false}
          destroyOnClose={true}
          style={{ position: 'absolute' }}
          width='90%'
        >
          <AlarmDetail alarmOrd={alarm.ord}/>
        </Drawer>
      </Card>
    );
  }
}

AlarmCard.propTypes = {
  searchParams: PropTypes.array.isRequired
}

export default connect(({ alarmData, loading }) => ({
  ...alarmData,
  loading: loading.effects['alarmData/fetch'],
}))(AlarmCard);
